<template>
  <!-- 只有广告组关键词才能设置最高每次点击费用 -->
  <el-dialog
    :visible.sync="show"
    :title="'添加'+title"
    class="yyy-dialog"
    :width="width"
    :before-close="handleClose"
    @open="handleOPen"
  >

    <slot />
    <div :class="borderShow?'word-box  border-box':'word-box'" style="display: flex; align-items: flex-start;justify-content: space-between;">

      <!-- 拓词 -->
      <div v-if="appid" class="left">
        <recommendWord v-if="appid" ref="recommendAdd" :appid="appid" :country-list="countryList" @handleAdd="recommendAdd"></recommendWord>
      </div>
      <div v-if="$route.name==='wordDetail'" class="left">
        <open-word @handleAdd="recommendAdd"></open-word>
      </div>

      <!-- 添加词 -->
      <div class="right" style="flex: 1;max-width: 740px;">
        <div v-if="!wordsChecked.length" class="add-box">
          <el-input
            v-model.trim="words"
            size="small"
            :placeholder="'添加'+title+'，用英文逗号分隔，对于精确匹配，使用括号括住关键词（即，[关键词]）'"
            @keyup.enter.native="handleAddWords"
          />
          <el-button size="small" type="success" @click="handleAddWords">
            <span style="font-size: 14px;">添加</span>
          </el-button>
        </div>
        <div v-else class="choose-box">
          <p class="num">
            <i class="el-icon-warning" />
            <span style="font-size: 14px;">
              已选择
              <em style="font-size: 14px;">{{ wordsChecked.length }}</em>项
            </span>
          </p>

          <template>
            <em v-show="exactIsClick" style="cursor: pointer;" @click="changeWordType('EXACT')">改为精准匹配</em>
            <em v-show="!exactIsClick" style="cursor: not-allowed;opacity: 0.8;color: #999;">改为精准匹配</em>
          </template>

          <template>
            <em v-show="broadClick" style="cursor: pointer;" @click="changeWordType('BROAD')">改为模糊匹配</em>
            <em v-show="!broadClick" style="cursor: not-allowed;opacity: 0.8;color: #999;">改为模糊匹配</em>
          </template>

          <el-popover v-if="feiYongShow" v-model="popoShow" placement="top" width="316" class="feiyong-input">
            <el-form ref="numberForm" :model="popoNunmber" :inline-message="true" @submit.native.prevent>
              <el-form-item prop="popoNunmber" :rules="amountRules1" style="margin-bottom: 0px;">
                <div class="flex">
                  <amountInput
                    v-model.number="popoNunmber.popoNunmber"
                    :controls="false"
                    :precision="2"
                    size="small"
                    style="width: 162px;"
                    @keyup.native.enter="changeFeiYong"
                  />
                  <el-button type="success" size="small" style="margin:0 12px;" @click="changeFeiYong">确定</el-button>
                  <em class="pointer" @click="popoFinOut">取消</em>

                </div>

              </el-form-item>
            </el-form>

            <em slot="reference" class="del">修改最高每次点击费用</em>
          </el-popover>

          <p class="del" @click="handleDelAll">移除</p>
        </div>
        <div>
          <el-form :ref="tableForm">

            <el-table ref="wordAddTable" :data="wordsData" class="series-table" height="400px" style="margin-top: 0;" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" :selectable="checkSelectable" />
              <el-table-column property="text" :label="title==='投放关键词'?'关键词 ('+wordsData.length+')':'屏蔽词 ('+wordsData.length+')'" show-overflow-tooltip align="left">

                <template slot-scope="scope">
                  <span v-html="scope.row.matchType==='BROAD'?htmlText(scope.row.text):'['+htmlText(scope.row.text)+']'"></span>
                </template>
              </el-table-column>
              <el-table-column v-if="feiYongShow" property="name" label="最高每次点击费用" align="left" width="180">
                <template slot-scope="scope">
                  <el-form-item style="margin-bottom: 0;" :prop="'wordsData.'+scope.$index+'.bidAmountNub'">
                    <amountInput
                      v-model="scope.row.bidAmountNub"
                      :controls="false"
                      :precision="2"
                      style="width: 80%;"
                      size="small"
                      class="amountInput-box"
                    />

                  </el-form-item>

                </template>
              </el-table-column>

              <el-table-column property="name" label="匹配类型" align="left" width="160">
                <template slot-scope="scope">
                  <el-form-item style="margin-bottom: 0px;" inline-message show-message>
                    <el-select
                      v-model="scope.row.matchType"
                      placeholder="请选择"
                      style="width: 80%;line-height:0"
                      size="small"
                      :disabled="!checkSelectable(scope.row)"
                      @change="handleRowTypeChange(scope.row)"
                    >
                      <el-option label="模糊匹配" value="BROAD" />
                      <el-option label="精确匹配" value="EXACT" />
                    </el-select>
                  </el-form-item>

                </template>
              </el-table-column>

              <el-table-column property="address" label="操作" width="80">
                <template slot-scope="scope">
                  <em v-if="!scope.row.id" style="cursor: pointer;font-size: 14px;" @click="handleDel([scope.row],scope.$index)">移除</em>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>

    </div>

    <!-- <slot ></slot> -->

    <div slot="footer" class="footer">
      <el-button size="small" class="cancel-btn defult" @click="handleClose">取消</el-button>
      <el-button type="success" size="small" class="defult" style="width: 80px;" @click="handleSub">保存</el-button>
    </div>
  </el-dialog>

</template>

<script>
import amountInput from '@/components/amountInput/index.vue'
import recommendWord from '@/components/recommendWord/index.vue'
import openWord from '@/components/openWord/index.vue'
export default {
  components: {
    amountInput,
    recommendWord,
    openWord
  },
  props: {
    // 标题名称
    title: {
      default: '关键词',
      type: String
    },
    // 是否显示
    visible: {
      default: false
    },
    // 是否显示最高点击费用
    feiYongShow: {
      default: false,
      type: Boolean
    },
    // 传进来的词语组合
    wordsList: {
      default: () => {
        return []
      },
      type: Object
    },
    // 在点击保存按钮之前的行数
    beforeSub: {
      type: Function,
      default: () => {
        return true
      }
    },

    appid: {
      type: String || Number

    },

    countryList: {
      type: String || Object
    },

    // 点击费用最大值
    maxNum: {
      default: 1,
      type: Number
    },
    // 默认最高点击出价
    defaultNum: {
      default: 0.01,
      type: Number
    },
    width: {
      type: String,
      default: () => {
        return '780px'
      }
    }
  },
  data() {
    const validateMount = (rule, value, callback) => {
      if (value * 100 < 1 || value === undefined || value === '') {
        callback(new Error('您的出价必须至少为 $0.01'))
      } else if (value > 1000) {
        callback(new Error('您的出价不得高于$1000.00'))
      } else if (value * 100 > this.maxNum * 100) {
        callback(new Error('您的出价不能大于' + this.maxNum.toFixed(2)))
      } else {
        callback()
      }
    }
    const validateMount1 = (rule, val, callback) => {
      const value = this.popoNunmber.popoNunmber
      if (value * 100 < 1 || value === undefined || value === '') {
        callback(new Error('您的出价必须至少为 $0.01'))
      } else if (value > 1000) {
        callback(new Error('您的出价不得高于$1000.00'))
      } else if (value * 100 > this.maxNum * 100) {
        callback(new Error('您的出价不能大于' + this.maxNum.toFixed(2)))
      } else {
        callback()
      }
    }
    return {
      amountRules: [{
        validator: validateMount,
        trigger: 'blur'
      }],
      amountRules1: [{
        validator: validateMount1,
        trigger: 'blur'
      }],
      exactIsClick: true, // 改为精准匹配按钮是否能被点击
      broadClick: true, // 改为模糊匹配按钮是否能被点击
      words: '', // 输入框的值
      show: false, // 组件是否显示
      wordsData: [

        // {
        //   bidAmount: {
        //     amount: 0,
        //     currency: 'USD'
        //   }, //最高费用
        //   matchType: 'EXACT', //匹配类型
        //   text: undefined, //名称
        // }
      ], // 关键词等表格数据
      wordsChecked: [], // 勾选中的关键词等
      popoShow: false, // 批量修改最高每次点击费用弹窗的显示
      popoNunmber: {
        popoNunmber: undefined
      }, // 批量修改最高每次点击费用弹窗/输入框的值
      formLabelWidth: '120px'
    }
  },
  computed: {
    borderShow() {
      if (this.$route.name === 'seriesOverview') {
        return true
      } else {
        return false
      }
    }
  },

  watch: {
    // 显示
    visible() {
      this.show = this.visible
      this.$nextTick(() => {
        this.$refs['wordAddTable'].doLayout()
      })
    },
    maxNum: {
      deep: true,
      immediate: true,
      handler: function(newval, oldval) {}
    },
    // 关键词/屏蔽词数据
    wordsList: {
      deep: true,
      handler: function(newval, oldval) {
        this.wordsData = JSON.parse(JSON.stringify(newval))
      }
    },

    wordsChecked: {
      deep: true,
      handler: function(newval, oldval) {
        // 查看全部是否为精确匹配
        const allEx = this.wordsChecked.every(item => {
          return item.matchType === 'EXACT'
        })
        if (allEx) {
          this.exactIsClick = false
          this.broadClick = true
        }

        // 查看是否为模糊匹配
        const allBro = this.wordsChecked.every(item => {
          return item.matchType === 'BROAD'
        })

        if (allBro) {
          this.exactIsClick = true
          this.broadClick = false
        }

        if (!allEx && (!allBro)) {
          this.exactIsClick = true
          this.broadClick = true
        }
      }
    }

  },
  mounted() {
    this.wordsData = JSON.parse(JSON.stringify(this.wordsList))
  },
  methods: {
    htmlText(text) {
      return text.replace(/\ /g, '&nbsp;')
    },
    handleOPen() {
      /* console.log('你好') */
      if (this.appid && this.$refs['recommendAdd']) {
        this.$refs['recommendAdd'].searchStr = ''
        this.$refs['recommendAdd'].getWordFromAppId()
      }
      return false
    },
    // 点击了取消按钮
    handleClose() {
      if (this.wordsData.length > 0) {
        this.$confirm(`当前选择${this.title}尚未保存,确认关闭?`, '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'

        }).then(() => {
          this.words = undefined
          this.wordsData = JSON.parse(JSON.stringify(this.wordsList))
          this.wordsChecked = []
          this.$refs['wordAddTable'].clearSelection()
          this.$refs['wordAddTable'].doLayout()
          this.$emit('update:visible', false)
        })
      } else {
        this.words = undefined
        this.wordsData = JSON.parse(JSON.stringify(this.wordsList))
        this.wordsChecked = []
        this.$refs['wordAddTable'].clearSelection()
        this.$refs['wordAddTable'].doLayout()
        this.$emit('update:visible', false)
      }
    },
    // 保存
    handleSub() {
      const res = this.beforeSub()
      if (!res) return false

      if (this.feiYongShow) {
        const flag = this.wordsData.every(item => {
          if (item.bidAmountNub * 100 < 1 || item.bidAmountNub === undefined || item.bidAmountNub ===
              '') {
            this.$message.closeAll()
            this.$message.error('您的出价必须至少为 $0.01')
            return false
          } else if (item.bidAmountNub * 1 > 1000) {
            this.$message.closeAll()
            this.$message.error('您的出价不得高于$1000.00')
            return false
          } else if (item.bidAmountNub * 1 > this.maxNum) {
            this.$message.closeAll()
            this.$message.error('您的出价不能大于' + this.maxNum.toFixed(2))
            return false
          } else {
            return true
          }
        })
        if (!flag) {
          return false
        }
      }

      let num = 0
      this.wordsData.forEach(item => {
        if (!item.id) {
          num++
        }
      })

      if (num > 5000) {
        this.$message.closeAll()
        this.$message({
          showClose: true,
          message: '批量上传关键词最多上传5000个',
          type: 'warning'
        })
        return
      } else {
        this.$emit('handleSub', this.wordsData)
        this.wordsChecked = []
        this.wordsData = []
        this.$refs['wordAddTable'].clearSelection()
        this.$refs['wordAddTable'].doLayout()
        this.$emit('update:visible', false)
      }
    },

    // 添加词语的操作
    handleAddWords() {
      // 将输入框的字符串变成数组
      var wordArr = this.words.indexOf(',') > -1 ? this.words.split(',') : [this.words]
      wordArr = wordArr.filter(item => {
        return item !== null && item !== undefined && item.trim() !== ''
      })
      wordArr = wordArr.map(item => {
        return item.replace(/\s+/ig, ' ')
      })
      let dimArr = [] // 模糊匹配数组
      let exactArr = [] // 精确匹配数组
      const reuseArr = [] // 重复的数组
      const overstepArr = [] // 超过长度的数组
      // 清空一下输入框
      this.words = ''
      // 循环数据；
      wordArr.forEach(item => {
        if (item[0] === '[' && item[item.length - 1] === ']') {
          // 精确匹配:判断是否有[],取出字段
          let str = item.substring(1)
          str = str.substring(0, str.length - 1)
          if (exactArr.indexOf(str) == -1) {
            if (str.length > 80) {
              overstepArr.push(str)
            } else {
              exactArr.push(str)
            }
          } else {
            reuseArr.push(str)
          }
        } else {
          // 模糊匹配
          if (dimArr.indexOf(item) === -1) {
            if (item.length > 80) {
              overstepArr.push(item)
            } else {
              dimArr.push(item)
            }
          } else {
            reuseArr.push(item)
          }
        }
      })

      // 判断模糊匹配数据是否已经被添加,过滤出没被添加的词语
      dimArr = dimArr.filter(str => {
        const index = this.wordsData.findIndex(item => {
          return item.text === str && item.matchType === 'BROAD'
        })

        if (index < 0) return true
        reuseArr.push(str)
      })
      // 判断精确匹配匹配数据是否已经被添加,过滤出没被添加的词语
      exactArr = exactArr.filter(str => {
        const index = this.wordsData.findIndex(item => {
          return item.text === str && item.matchType !== 'BROAD'
        })
        if (index < 0) return true
        reuseArr.push(str)
      })

      /* 如果重复数组有数据，或者是字符创超过80数组有数据 */
      if (reuseArr.length || overstepArr.length) {
        let msg = ''
        if (reuseArr.length) {
          msg += `${reuseArr[0]}等${reuseArr.length}个字符重复，已自动过滤`
        }

        if (overstepArr.length) {
          msg += `<br/>有${overstepArr.length}个字符长度超过80,已自动过滤`
        }
        this.$message({
          type: 'warning',
          dangerouslyUseHTMLString: true,
          message: msg
        })
      }

      /* 算出最终数据*/
      let addArr = []
      dimArr.forEach(item => {
        addArr.push({
          text: item,
          matchType: 'BROAD'
        })
      })
      exactArr.forEach(item => {
        addArr.push({
          text: item,
          matchType: 'EXACT'
        })
      })

      // 如果有最高每次点击费用显示
      if (this.feiYongShow) {
        addArr = addArr.map(item => {
          const obj = { ...item
          }
          const num = isNaN(this.defaultNum) ? 0.01 : this.defaultNum.toFixed(2)
          obj.bidAmountNub = num > this.maxNum ? this.maxNum.toFixed(2) : num
          return obj
        })
      }

      this.wordsData = [...this.wordsData, ...addArr]

      // console.log(data, this.words,'你好这是添加关键词')
    },

    // 表格是否可以勾选的办法
    checkSelectable(row, index) {
      const str = row.text
      let num = 0
      this.wordsData.forEach(item => {
        if (item.text === str) num++
      })
      if (num > 1) {
        return false
      } else {
        return true
      }
    },

    // 表格勾选变化时候的数据
    handleSelectionChange(data) {
      this.wordsChecked = JSON.parse(JSON.stringify(data))
    },

    // 表格单行改变
    handleRowTypeChange(row) {
      // this.$refs['wordAddTable'].selectionChange()
      const arr = this.wordsChecked.map(item => {
        if (item.text === row.text) {
          item.matchType = row.matchType
        }
        return item
      })
      this.wordsChecked = arr
    },

    // 批量改变匹配类型
    changeWordType(type) {
      const arr = JSON.parse(JSON.stringify(this.wordsChecked))
      arr.forEach((item, index) => {
        // 改变勾选数据
        this.wordsChecked[index].matchType = type // 匹配类型；
        // 改变表格数据
        const index1 = this.wordsData.findIndex(v => {
          return v.text === item.text
        })

        if (index1 > -1) {
          this.wordsData[index1].matchType = type // 匹配类型；
        }
      })
    },

    // 批量移除
    handleDelAll() {
      this.handleDel(this.wordsChecked)
    },
    // 移除
    handleDel(data) {
      const delObj = JSON.parse(JSON.stringify(data))
      delObj.forEach(item => {
        const index = this.wordsData.findIndex(v => {
          return v.text === item.text && v.matchType === item.matchType
        })

        this.wordsData.splice(index, 1)
      })
      this.$emit('delWords', delObj)
    },
    // 修改最高点击费用取消
    popoFinOut() {
      this.$refs['numberForm'].resetFields()
      this.popoShow = false
      this.popoNunmber.popoNunmber = undefined
    },
    // 批量修改最高每次点击费用
    changeFeiYong() {
      this.$refs['numberForm'].validate((valid) => {
        if (valid) {
          this.wordsChecked.forEach(item => {
            const index = this.wordsData.findIndex(v => {
              return v.text === item.text
            })
            if (index > -1) {
              this.wordsData[index].bidAmountNub = this.popoNunmber.popoNunmber //
            }
          })
          this.popoShow = false
          this.popoNunmber.popoNunmber = undefined
        }
      })
    },
    recommendAdd(data) {
      const wordArr = data
      const dimArr = [] // 模糊匹配数组
      const exactArr = [] // 精确匹配数组
      const reuseArr = [] // 重复的数组
      const overstepArr = [] // 超过长度的数组

      // 循环词语数组,提取出重复数组和超过长度的数组
      wordArr.forEach(str => {
        if (str.length > 80) {
          overstepArr.push(str)
        }
        const dimIndex = this.wordsData.findIndex(item => {
          return item.text === str && item.matchType === 'BROAD'
        })
        const exactIndex = this.wordsData.findIndex(item => {
          return item.text === str && item.matchType !== 'BROAD'
        })
        // 如果既有模糊匹配，又会精确匹配，进入重复数组里面
        if (dimIndex !== -1 && exactIndex !== -1) {
          reuseArr.push(str)
        }
      })

      // 过滤出数据
      wordArr.filter(str => {
        return reuseArr.indexOf(str) === -1 && overstepArr.indexOf(str)
      })

      // 再次循环数据  判断字段是进入模糊匹配还是精确匹配
      wordArr.forEach(str => {
        // 如果在表格中没有存在模糊匹配的对应词
        const index = this.wordsData.findIndex(item => {
          return item.text === str && item.matchType === 'BROAD'
        })
        if (index === -1 && dimArr.indexOf(str) === -1) {
          // 如果表格模糊匹配数组里面没有，当前模糊匹配数组里面也没有  就增加到模糊匹配数组里面
          dimArr.push(str)
        } else {
          const index1 = this.wordsData.findIndex(item => {
            return item.text === str && item.matchType !== 'BROAD'
          })
          if (index1 === -1 && exactArr.indexOf(str) === -1) {
            exactArr.push(str)
          } else {
            reuseArr.push(str)
          }
        }
      })

      // 提示有重复的数据
      /* 如果重复数组有数据，或者是字符创超过80数组有数据 */
      if (reuseArr.length || overstepArr.length) {
        let msg = ''
        if (reuseArr.length) {
          msg += `${reuseArr[0]}等${reuseArr.length}个字符重复，已自动过滤`
        }

        if (overstepArr.length) {
          msg += `<br/>有${overstepArr.length}个字符长度超过80,已自动过滤`
        }
        this.$message({
          type: 'warning',
          dangerouslyUseHTMLString: true,
          message: msg
        })
      }

      if (exactArr.length) {
        let msg = ''
        if (exactArr.length < 5) {
          msg = `【${exactArr.join(',')}】`
        } else {
          const subArr = exactArr.slice(0, 4)
          msg += `【${subArr.join(',')}】等${exactArr.length}个关键词`
        }

        this.$confirm(`您上传的${msg}已存在“模糊匹配”,是否另外添加为“精确匹配”?`, '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          const dimAdd = dimArr.map(item => {
            return {
              text: item,
              matchType: 'BROAD'
            }
          })
          const exactAdd = exactArr.map(item => {
            return {
              text: item,
              matchType: 'EXACT'
            }
          })
          const addArr = [...dimAdd, ...exactAdd]
          if (this.feiYongShow) {
            addArr.map(item => {
              const num = isNaN(this.defaultNum) ? 0.01 : this.defaultNum.toFixed(2)
              item.bidAmountNub = num > this.maxNum ? this.maxNum.toFixed(2) : num
              return item
            })
          }
          this.wordsData = [...this.wordsData, ...addArr]
        }).catch(() => {
          const arr = dimArr.map(item => {
            const obj = {
              text: item,
              matchType: 'BROAD'
            }
            if (this.feiYongShow) {
              const num = isNaN(this.defaultNum) ? 0.01 : this.defaultNum.toFixed(2)
              obj.bidAmountNub = num > this.maxNum ? this.maxNum.toFixed(2) : num
            }
            return obj
          })
          this.wordsData = [...this.wordsData, ...arr]
        })
      } else {
        const arr = dimArr.map(item => {
          const obj = {
            text: item,
            matchType: 'BROAD'
          }
          if (this.feiYongShow) {
            const num = isNaN(this.defaultNum) ? 0.01 : this.defaultNum.toFixed(2)
            obj.bidAmountNub = num > this.maxNum ? this.maxNum.toFixed(2) : num
          }
          return obj
        })
        this.wordsData = [...this.wordsData, ...arr]
      }
    }
  }
}
</script>
<style lang="scss" scoped="true">
  @import "~@/styles/variables.scss";

  .yyy-dialog {
    ::v-deep .el-dialog__header {

      .head {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title {
          font-size: 20px;
          color: #303134;
        }

        i {
          font-size: 30px;
          color: #BDBDBD;
        }
      }

    }

    ::v-deep .el-dialog__body {

      .add-box {
        display: flex;
        width: 100%;
        margin-bottom: 20px;

        .el-input {
          flex: 1;
          margin-right: 24px;
        }
      }

    }
  }

  .choose-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    background: #E6F7FF;
    border: 1px solid $mainColor1;
    border-radius: 2px;
    padding: 6px 24px;

    // em,p{
    //   font-size: 14px;
    // }
    .num {
      display: flex;
      align-items: center;

      i {
        font-size: 20px;
        color: $mainColor1;
        margin-right: 14px;
      }

      span {
        font-size: 14px;

        em {
          padding: 0 4px;
          color: $mainColor1;
        }
      }
    }

    .type {

      span {
        color: #8F939B;
        margin-right: 80px;
        cursor: pointer;

        &.active {
          color: $mainColor1;
        }
      }
    }

    .del {
      cursor: pointer;
      color: $mainColor1;
    }
  }

  .series-table ::v-deep .el-table__header-wrapper {

    thead {

      // background-color: red;
      tr {

        background-color: #f1f1f1 !important;
      }
    }

  }

  .border-box {
    border-top: 1px solid #eee;

    .right {
      padding-top: 20px;
    }

    .left>div {
      padding-top: 20px;
    }
  }

 .yyy-dialog /deep/ .amountInput-box {
    input{
      padding-left: 12px !important;
      text-align: left;
    }
  }

  .yyy-dialog /deep/ .el-popover{
    .el-form-item__content{
      line-height: 12px;
    }
  }
</style>
